import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { AxiosHeaders } from 'axios';  // Import AxiosHeaders
import { showNotification } from './notify';
const baseURL = import.meta.env.VITE_API_BASE_URL;


// 创建 axios 实例
const service = axios.create({
  baseURL: baseURL, // 后端接口的基础 URL
  timeout: 5000 // 请求超时时间
});

// 请求拦截器

service.interceptors.request.use((config) => {
    const token = localStorage.getItem('token');
    if (token) {
        let headers: AxiosHeaders; //Explicit type annotation
        if (config.headers) {
            if(config.headers instanceof AxiosHeaders) {
               headers = config.headers;
            } else {
               headers = new AxiosHeaders(config.headers) // Copy potentially existing headers
            }

        } else {
            headers = new AxiosHeaders();
        }
        headers.set('Authorization', token);
        config.headers = headers;
    }
    return config;
});

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    const { code, message } = response.data;
    if (code !== 200) {
      // 处理业务错误，例如登录失败、权限不足等
      showNotification('响应出错:'+message, true)
      return Promise.reject(new Error(message));
    }
    return response.data;
  },
  (error) => {
    // 处理响应错误，例如网络错误、服务器错误等
    showNotification('响应出错:'+error.message, true)
    return Promise.reject(error);
  }
);

// 封装请求方法
const request = {
  get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, config).then((res) => res as T);
  },
  post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config).then((res) => res as T);
  },
  put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config).then((res) => res as T);
  },
  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config).then((res) => res as T);
  }
};

export default request;